package com.kamistoat.meimeimall.meimeimallsearch.dubbo;

import com.kamistoat.meimeimall.common.To.EsTo.RegisterUpTo;
import com.kamistoat.meimeimall.common.To.EsTo.SpuUpTo;
import com.kamistoat.meimeimall.common.annotation.DubboAndHTTPExceptionCatch;
import com.kamistoat.meimeimall.common.dubboInterface.SearchDubboInterface;
import com.kamistoat.meimeimall.common.exception.BizCodeEnum;
import com.kamistoat.meimeimall.common.exception.RRException;
import com.kamistoat.meimeimall.common.utils.R;
import com.kamistoat.meimeimall.meimeimallsearch.service.ElasticSaveService;
import io.seata.core.constants.DubboConstants;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Service
@Component
public class SearchDubboInterfaceImpl implements SearchDubboInterface {
    @Autowired
    ElasticSaveService elasticSaveService;

    /**
     * 将 用户名-手机号 添加到ES检索
     *
     * @param registerUpTo 对象
     * @return R
     */
    @DubboAndHTTPExceptionCatch
    @Override
    public R registerUpToES(RegisterUpTo registerUpTo) {
        try {
            elasticSaveService.registerUpToEs(registerUpTo);
            return R.ok();
        } catch (IOException e) {
            throw new RRException(e.getMessage(), BizCodeEnum.ES_INDEX_EXCEPTION.getCode());
        }
    }

    /**
     * 从ES中检索 用户名 是否存在
     *
     * @param username 用户名
     * @return R
     */
    @DubboAndHTTPExceptionCatch
    @Override
    public R usernameUniqueES(String username) {
        try {
            Boolean aBoolean = elasticSaveService.usernameUniqueES(username);
            if (aBoolean) {
                throw new RRException(BizCodeEnum.USERNAME_EXIST_EXCEPTION.getMessage(), BizCodeEnum.USERNAME_EXIST_EXCEPTION.getCode());
            }
            return R.ok();
        } catch (IOException e) {
            throw new RRException(e.getMessage(), BizCodeEnum.ES_SEARCH_EXCEPTION.getCode());
        }
    }

    /**
     * 将Spu上架到ES中
     *
     * @param spuUpToList
     * @return
     */
    @Override
    @DubboAndHTTPExceptionCatch
    public R spuUpToES(List<SpuUpTo> spuUpToList) {
        try {
            elasticSaveService.spuUpToES(spuUpToList);
            return R.ok();
        } catch (IOException e) {
            throw new RRException(e.getMessage(), BizCodeEnum.ES_INDEX_EXCEPTION.getCode());
        }
    }

    /**
     * 将一系列sku商品从ES中下架
     *
     * @param skuIds
     * @return
     */
    @Override
    @DubboAndHTTPExceptionCatch
    public R skuDownToES(List<Long> skuIds) {
        try {
            elasticSaveService.spuDownToES(skuIds);
            return R.ok();
        } catch (IOException e) {
            throw new RRException(e.getMessage(), BizCodeEnum.ES_INDEX_EXCEPTION.getCode());
        }
    }
}
